package com.qf.j2205.filter;


import com.qf.j2205.entity.AdminInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName AutoFilter
 * @Description TODO
 * @Author Windy
 * @Date 2022/8/15 17:02
 * @Version 1.0
 **/
public class AutoFilter implements Filter {
    //需要定义系统页面访问中可放行的连接
    private List<String> list = new ArrayList<String>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        list.add("/Login.html");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取页面中的访问的路径连接
        String path = request.getServletPath();
        if(list!=null && list.contains(path)){
            //如果页面中获取的访问连接于定义的可放行的连接一致，则放行
            filterChain.doFilter(request, response);
            return;
        }
        //2、从session(admin_user)对象中获取当前登录的用户
        AdminInfo elecUser = (AdminInfo) request.getSession().getAttribute("admin_user");
        if(elecUser!=null){
            //如果从session中获取的用户对象不为空，则放行
            filterChain.doFilter(request, response);
            return;
        }
        //如果不满足条件1和2，则不能放行，回到系统的登录页面 request.getContextPath()获取根路径
        response.sendRedirect(request.getContextPath()+"/");
    }

    @Override
    public void destroy() {

    }
}
